package com.slc.filemanage.client;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传下载管理类
 * Created by sunguangzhu on 2015/3/6.
 */
public class FileManageUtil {
    /**
     * 文件上传
     * @param url
     * @param fileMap
     * @param secondDir
     * @param createDateDir
     * @return
     * @throws IOException
     */
    public static boolean upload(String url,Map<String, File> fileMap,String secondDir,boolean createDateDir) throws IOException {
        if(secondDir==null){
            secondDir="";
        }
        if (fileMap == null || fileMap.size() == 0) {
            return false;
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url + "/file/upload");

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式
        multipartEntityBuilder.addPart("secondDir", new StringBody(secondDir, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("createDateDir", new StringBody(Boolean.valueOf(createDateDir).toString(), ContentType.DEFAULT_TEXT));
        for (String key : fileMap.keySet()) {
            multipartEntityBuilder.addPart(key, new FileBody(fileMap.get(key)));
        }
        HttpEntity entity = multipartEntityBuilder.build();
        httppost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httppost);
        try {
            EntityUtils.consume(httpResponse.getEntity());
        } finally {
            httpResponse.close();
        }
        return true;
    }

    /**
     * 文件上传
     *
     * @param url       文件服务器url
     * @param fileMap   文件的map
     * @param secondDir 二级目录
     * @return true or false
     * @throws IOException
     */
    public static boolean upload(String url, Map<String, File> fileMap, String secondDir) throws IOException {
        return upload(url, fileMap, secondDir,false);
    }

    /**
     * 文件下载
     *
     * @param url 文件服务器url
     * @return 流
     * @throws IOException
     */
    public static byte[] download(String url, String path) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url + "/file/download");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("path", path));
        HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
        httppost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httppost);
        HttpEntity entity1 = httpResponse.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity1);
        try {
            EntityUtils.consume(entity1);
        } finally {
            httpResponse.close();
        }
        return bytes;
    }

    public static void main(String[] args) throws IOException {
        Map<String, File> fileMap = new LinkedHashMap<String, File>();
//        fileMap.put("file2",new File("E:\\中文1.jpg"));
//        fileMap.put("file3",new File("E:\\3.jpg"));
//        fileMap.put("file3",new File("E:\\FeigeDownload\\溯源营销-2015升级版.doc"));
        fileMap.put("file3",new File("E:\\1.txt"));
        ;
        boolean upload = FileManageUtil.upload("http://localhost:8080/fm", fileMap,null);
        System.out.println("upload = " + upload);

//        byte[] bytes = FileManageUtil.download("http://192.168.100.110:8888/filemanage", "nmmc/20150309/中文1.jpg");
//
//        File storeFile = new File("E:/test/2222_copy.jpg");
//        FileOutputStream output = new FileOutputStream(storeFile);
//        //得到网络资源的字节数组,并写入文件
//        output.write(bytes);
//        output.flush();
//        output.close();
    }
}
